package com.zixi.ai.framework.dao.spec;

import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mqiqe
 */
public class LogicalExpression implements Criterion {
    /** 逻辑表达式中包含的表达式 */
    private final Criterion[] criterion;
    /** 计算符  */
    private final Operator operator;
  
    public LogicalExpression(Criterion[] criteria, Operator operator) {
        this.criterion = criteria;
        this.operator = operator;  
    }  
  
    @Override
	public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,  
            CriteriaBuilder builder) {  
        List<Predicate> predicates = new ArrayList<>();
        for (Criterion value : this.criterion) {
            predicates.add(value.toPredicate(root, query, builder));
        }
        return switch (operator) {
            case OR -> builder.or(predicates.toArray(new Predicate[0]));
            case AND -> builder.and(predicates.toArray(new Predicate[0]));
            default -> null;
        };
    }  
  
}  